/*
 * WebSocketRequestHandler.cpp
 *
 *  Created on: Apr 6, 2017
 *      Author: zhangjf
 */

#include <Poco/Thread.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <Poco/Net/NetException.h>
#include <Poco/Net/WebSocket.h>

using namespace Poco::Net;

#include "MainApplication.h"
#include "WebSocketNotificationnHandler.h"
#include "AppServNotificationnHandler.h"
#include "WebSocketRequestHandler.h"

WebSocketRequestHandler::WebSocketRequestHandler()
{
	// TODO Auto-generated constructor stub

}

WebSocketRequestHandler::~WebSocketRequestHandler()
{
	// TODO Auto-generated destructor stub
}

void WebSocketRequestHandler::handleRequest(HTTPServerRequest& request,
		HTTPServerResponse& response)
{
    try
    {
        WebSocket ws(request, response);
        poco_information(*pLogger, "WebSocket connection established.");
        StreamSocket ss(SocketAddress("127.0.0.1", 12345));
        poco_information(*pLogger, "AppServ connection established.");

        WebSocketNotificationnHandler thdWebSocket(ws, ss);
        AppServNotificationnHandler thdAppServ(ws, ss);

        Thread thd1;
        Thread thd2;

        thd1.start(thdWebSocket);
        thd2.start(thdAppServ);

        thd1.join();
        thd2.join();
    }
    catch (WebSocketException& exc)
    {
    	poco_information(*pLogger, "exception:: " + exc.displayText());
        switch (exc.code())
        {
        case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
            response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
            response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
            response.setContentLength(0);
            response.send();
            break;
           // fallthrough
        case WebSocket::WS_ERR_NO_HANDSHAKE:
        case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
        case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
            response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
            response.setContentLength(0);
            response.send();
            break;
        }
    }
}
